import tornado
import asyncio
import tornado.web


import chat
import config
config.load_config()
chat_bot = chat.Chat()
chat_bot.init("insurancePensionSteam", "123456")
from common.log import logger

class InitHandler(tornado.web.RequestHandler):
    """Update Forbidden Intent"""
    async def get(self):
        """update forbidden intent"""
        message = self.get_argument('message')#str(self.request.arguments.get('message')[0])

        user_id = self.get_argument('userId')
        user_name = self.get_argument('userName')
        init_scene = self.get_argument('initScene')
        reply = chat_bot.init(init_scene, user_id)

        # 存储用户和会话id对应关系
        return reply


class StreamHandler(tornado.web.RequestHandler):
    """Update Forbidden Intent"""
    async def get(self):
        """update forbidden intent"""

        message = self.get_argument('message')#str(self.request.arguments.get('message')[0])
        user_id = self.get_argument('userId')#str(self.request.arguments.get('userId')[0])
        chat_reply = await chat_bot.get_reply_by_stream(message, user_id)
        last_offset = 0
        finally_content = ""
        async for chunk in chat_reply:
            #logger.info("chunk：" + str(chunk))
            token_offset = len(chunk["text"])
            chunk_data = chunk["text"][last_offset:]
            last_offset = token_offset
            chunk_data = chunk_data.replace("�", "")
            self.write(chunk_data + "\n")
            await self.flush()
            finally_content += chunk_data
        logger.info("最终生成结果：" + finally_content)
        chat_bot.flush_conversation(finally_content, user_id)
        #response = Response(get_reply_by_stream)  # , content_type='application/octet-stream')
        #return response


app = tornado.web.Application([
    (r'/init', InitHandler),
    (r'/message_by_stream', StreamHandler),
])

if __name__ == '__main__':
    app.listen(9235)
    print('启动服务...')
    # logging.info('启动服务...')
    tornado.ioloop.IOLoop.instance().start()
